// 子模块moduleA路径：store/modules/moduleA.js
export default {
    // 命名空间
    namespaced: true,
    state: {
        list: uni.getStorageSync('hm-card') || [],

    },
    getters: {
        getChecked(state) {
            return state.list.filter(v => v.checked)
        },
        // 获取商品数量
        getCheckedNum(state, getters) {
            return getters.getChecked.reduce((s, v) => s + v.num, 0)
        },
        //获取商品总价格
        getTotalPice(state, getters) {
            return getters.getChecked.reduce((s, v) => s + v.num * v.goods_price, 0)
        },
        getCheckedAll(state, getters) {
            return state.list.length &&state.list.length === getters.getChecked.length
        },

    },
    mutations: {
        // 添加商品
        addCart(state, payload) {
            // payload =  goodsDetail

            // 判断商品是否存在 找到就返回数组下标 找不到就返回-1
            // v = list 中 每一个对象
            const index = state.list.findIndex(
                (v) => v.goods_id === payload.goods_id
            );
            if (index === -1) {
                // 没有购买过
                // 新增商品
                state.list.push({ ...payload, num: 1, checked: true });
            } else {
                // 已经购买过
                state.list[index].num++;
            }
            // console.log(state.list);
            // 将数据存在本地
            uni.setStorageSync('hm-card', state.list)
        },
        goodChecked(state, payload) {
            state.list[payload].checked = !state.list[payload].checked
            uni.setStorageSync('hm-card', state.list)
        },
        // 点击全选按钮的状态
        allChecked(state, payload, getters) {
            const allChecked = !this.getters['cart/getCheckedAll']
            state.list.forEach(v => v.checked = allChecked);
            uni.setStorageSync('hm-card', state.list)
        },
        numChange(state, payload) {
            state.list[payload.index].num += payload.num
            uni.setStorageSync('hm-card', state.list)
            
        },
        deleteGoods(state,payload) {
            state.list.splice(payload, 1)
            uni.setStorageSync('hm-card', state.list)
        }


    },
    actions: {},
};
